package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.FriendApi;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 分页查询好友信息
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<Friend> findPageByUserId(Long userId, Long page, Long pageSize) {

        // 统计总数
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);

        //计算开始行
        long start = (page - 1) * pageSize;

        // 定义需要返回的结果集
        List<Friend> friendList = new ArrayList<>();

        if(count > start){
            query.skip(start).limit(pageSize.intValue());
            // 分页查询好友表
            friendList = mongoTemplate.find(query, Friend.class);
        }
        return new PageResult<>(page,pageSize,count,friendList);
    }
}
